﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using LSQL;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using DevExpress.CodeParser;
using DevExpress.DashboardCommon.DataBinding;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.TextBox;

namespace Shopfloormanagement.Forms
{
    public partial class Topic_Action : DevExpress.XtraEditors.XtraForm
    {
        public static Topic_Action instance = new Topic_Action();
        public static bool isNewAction = false;
        public static bool isNewTopic = false;
        public Topic_Action()
        {
            instance = this;
            InitializeComponent();
        }

        //需要增加权限
        private void Topic_Action_Load(object sender, EventArgs e)
        {
            cbDepTopic.SelectedIndex = -1;
            cbResDep.SelectedIndex = -1;
            cbResPerson.SelectedIndex = -1;

            DataTable dtDepartment = new DataTable();
            if (SystemInfo.readparentDep == 0)
            {
                dtDepartment = SQL.ReturnDataTable3(SystemInfo.SQL, "Departments", $"ParentDepartmentID = 0 and Del_tag = 0");
                publicFunc.ComboBoxInit(dtDepartment, cbDepTopic, "DepartmentName", "ID");
                publicFunc.ComboBoxInit(dtDepartment, cbResDep, "DepartmentName", "ID");
            }
            else
            {
                string queryPeerDep = $@"WITH 
  -- 获取目标部门（ID=61）的父部门ID
  TargetDept AS (
    SELECT ID, ParentDepartmentID 
    FROM departments 
    WHERE ID = {SystemInfo.readparentDep}
  ),

  -- 平级部门（与 ID=61 同一父级的其他部门）
  PeerDepartments AS (
    SELECT 
      d.ID,
      d.DepartmentName,
      d.ParentDepartmentID,
      NULL AS Level,          -- 平级部门无层级，设为 NULL
      'Peer' AS RelationshipType
    FROM departments d
    INNER JOIN TargetDept td 
      ON d.ParentDepartmentID = td.ParentDepartmentID
    WHERE d.ID <> {SystemInfo.readparentDep} and Del_tag = 0         -- 排除自身
  ),

  -- 子部门（递归查询 ID=61 的所有下级部门）
  ChildDepartments AS (
    -- 初始层：目标部门自身
    SELECT 
      ID,
      DepartmentName,
      ParentDepartmentID,
      0 AS Level,             -- 层级从 0 开始
      'Child' AS RelationshipType
    FROM departments 
    WHERE ID = {SystemInfo.readparentDep} and Del_tag = 0

    UNION ALL

    -- 递归层：逐级向下查找子部门
    SELECT 
      d.ID,
      d.DepartmentName,
      d.ParentDepartmentID,
      cd.Level + 1 AS Level,  -- 层级递增
      'Child' AS RelationshipType
    FROM departments d
    INNER JOIN ChildDepartments cd 
      ON d.ParentDepartmentID = cd.ID
  )

-- 合并结果（平级部门 + 子部门）
SELECT 
  ID,
  DepartmentName,
  ParentDepartmentID,
  RelationshipType,
  Level
FROM (
  SELECT * FROM PeerDepartments
  UNION ALL
  SELECT * FROM ChildDepartments
) CombinedResult
ORDER BY 
  RelationshipType DESC,  -- 平级在前，子级在后
  Level;";
                DataTable dt = SQL.ReturnDataTable(SystemInfo.SQL, queryPeerDep);
                string[] idArray = new string[dt.Rows.Count + 1];
                idArray[0] = SystemInfo.readparentDep.ToString();
                if (dt.Rows.Count > 0)
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        idArray[i + 1] = dt.Rows[i]["ID"].ToString();
                    }

                }
                string ids = string.Join(",", idArray);

                DataTable dtRela = SQL.ReturnDataTable3(SystemInfo.SQL, "DepRelation", $"mainDepID = {SystemInfo.readparentDep} and Del_tag = 0 and isConfirm = 1");
                string[] idArray1 = new string[dtRela.Rows.Count];
                if (dtRela.Rows.Count > 0)
                {
                    for (int j = 0; j < dtRela.Rows.Count; j++)
                    {
                        idArray1[j] = dtRela.Rows[j]["DepID"].ToString();
                    }
                    string ids1 = string.Join(",", idArray1);
                    ids = ids + "," + ids1;
                }

                dtDepartment = SQL.ReturnDataTable3(SystemInfo.SQL, "Departments", $"ID in ({ids}) and Del_tag = 0");
                publicFunc.ComboBoxInit(dtDepartment, cbDepTopic, "DepartmentName", "ID");
                publicFunc.ComboBoxInit(dtDepartment, cbResDep, "DepartmentName", "ID");
            }
            //加载同级部门及子部门

            if (isNewTopic)
            {
                isNewAction = true;
                dtpDateTopic.DateTime = DateTime.Now.Date;
                btnSaveTopic.Text = "Save new";
                //查询部门，需要是当前阅读部门下的所有部门
                string depList = SystemInfo.readparentDep.ToString();
                publicFunc.ComboBoxInit(dtDepartment, cbDepTopic, "DepartmentName", "ID");
            }
            else
            {
                if (TopicID != 0)
                {
                    btnSaveTopic.Text = "Save edit";
                    string depList = SystemInfo.readparentDep.ToString();
                    //publicFunc.ComboBoxInit(dtDepartment, cbDepTopic, "DepartmentName", "ID");

                    DataTable dtOld = SQL.ReturnDataTable3(SystemInfo.SQL, "View_Topic", $"ID = {TopicID}");
                    dtpDateTopic.DateTime = Convert.ToDateTime(dtOld.Rows[0]["DateTime"]);
                    txtTopic.Text = dtOld.Rows[0]["TopicINFO"].ToString();
                    cbDepTopic.Tag = (int)dtOld.Rows[0]["DepartmentID"];
                    cbDepTopic.Text = dtOld.Rows[0]["Department"].ToString();
                    chkEscalation.Checked = (bool)dtOld.Rows[0]["isEscalation"];
                    chkCIP.Checked = (bool)dtOld.Rows[0]["isCIP"];

                    //下方history显示
                    DataTable topicHis = SQL.ReturnDataTable3(SystemInfo.SQL, "View_TopicHistory", $"Topic_ID = {TopicID}");
                    gcTopicHistory.DataSource = topicHis;
                }

            }

            if (isNewAction)
            {
                btnSave.Text = "Save new";
                dtpDueon.DateTime = DateTime.Now.Date;
                //查询部门，需要是当前阅读部门下的所有部门
                string depList = SystemInfo.readparentDep.ToString();

            }
            else
            {
                if (TodoID != 0)
                {
                    btnSave.Text = "Save edit";

                    string depList = SystemInfo.readparentDep.ToString();
                    DataTable dtOld = SQL.ReturnDataTable3(SystemInfo.SQL, "View_Todo", $"ID = {TodoID}");
                    dtpDueon.DateTime = Convert.ToDateTime(dtOld.Rows[0]["DueDate"]);
                    txtRootCause.Text = dtOld.Rows[0]["RootCause"].ToString();
                    txtTodo.Text = dtOld.Rows[0]["TodoINFO"].ToString();
                    txtTodo.Text = dtOld.Rows[0]["TodoINFO"].ToString();
                    cbResDep.Text = dtOld.Rows[0]["负责部门"].ToString();
                    cbResDep.Tag = (int)dtOld.Rows[0]["负责部门ID"];
                    resDepID = (int)dtOld.Rows[0]["负责部门ID"]; ;
                    cbResPerson.Text = dtOld.Rows[0]["负责人姓名"].ToString();
                    cbResPerson.Tag = (int)dtOld.Rows[0]["负责人ID"];
                    resPersonID = (int)dtOld.Rows[0]["负责人ID"];
                    isConfirmation = Convert.ToInt32(dtOld.Rows[0]["isConfirmation"]);

                    //下方history显示
                    DataTable todoHis = SQL.ReturnDataTable3(SystemInfo.SQL, "View_todo_History", $"[Todo ID] = {TodoID}");
                    gcActionHistory.DataSource = todoHis;

                }


            }

        }

        public static int TopicID;
        public static int resDepID = 0;
        public static int resPersonID = 0;

        private void cbResDep_SelectedValueChanged(object sender, EventArgs e)
        {
            cbResPerson.Properties.Items.Clear();
            cbResPerson.SelectedIndex = -1;
            // 获取选中的项的Tag
            var selectedItem = cbResDep.SelectedItem as publicFunc.ComboBoxItem;
            if (selectedItem != null)
            {
                var tag = selectedItem.Tag; // 这里可以使用tag
                resDepID = Convert.ToInt32(tag);
                Console.WriteLine("Res. dep = " + tag);

                //根据tag的ID查询用户
                int depID = Convert.ToInt32(tag);
                DataTable dtUser = SQL.ReturnDataTable3(SystemInfo.SQL, "View_EmployeeDepartments", $"DepartmentID = {depID}");

                if (dtUser.Rows.Count > 0)
                {

                    publicFunc.ComboBoxInit(dtUser, cbResPerson, "FullName", "EmployeeID"); // 载入部门人员

                }

            }
        }

        private void cbResPerson_SelectedValueChanged(object sender, EventArgs e)
        {
            var selectedItem = cbResPerson.SelectedItem as publicFunc.ComboBoxItem;
            if (selectedItem != null)
            {
                var tag = selectedItem.Tag; // 这里可以使用tag
                resPersonID = Convert.ToInt32( tag);
                Console.WriteLine("Res. person = " + tag);
            }
        }

        public static int TodoID;
        public static int Status;
        public static int isConfirmation;
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (isNewAction)
            {
                if (txtTodo.Text == "")
                {
                    XtraMessageBox.Show("请输入解决方案！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;

                }

                //TopicID = 40425;
                string due = dtpDueon.DateTime.ToString();
                string root = txtRootCause.Text;
                string todo = txtTodo.Text;

                //string columns = "[TopicID], [RootCause], [TodoINFO], [RespDepartmentID], [RespUserID], [DueDate], [Create_time], [Create_userID]";
                //string values = $"{TopicID},'{root}','{todo}',{resDepID},{resPersonID},'{due}','{DateTime.Now}',{SystemInfo.userID}";
                //int res = SQL.Insert(SystemInfo.SQL, "Todo", columns, values);

                string[] columnNames = { "TopicID", "RootCause", "TodoINFO", "RespDepartmentID", "RespUserID", "DueDate", "Status", "isConfirmation", "Create_time", "Create_userID", "Del_tag" };
                object[] columnValues = { TopicID, root, todo, resDepID, resPersonID, due, 1, 0, DateTime.Now, SystemInfo.userID, 0 };
                int res = SQL.InsertDataAndGetId(SystemInfo.SQL, "Todo", columnNames, columnValues);

                if (res > 0)
                {
                    //写入历史
                    string Items = "Type,TopicID,RootCause,TodoINFO,RespDepartmentID,RespUserID,DueDate,Status,isConfirmation,Create_time,Create_userID,Todo_ID,Del_tag";
                    string Values = $"'{"新增"}',{TopicID},'{txtRootCause.Text}','{txtTodo.Text}',{resDepID},{resPersonID},'{dtpDueon.DateTime.ToString()}',{0},{0},'{DateTime.Now}','{SystemInfo.userID}',{res},{0}";
                    SQL.Insert(SystemInfo.SQL, "Todo_history", Items, Values);

                    XtraMessageBox.Show("数据已成功保存！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    DialogResult result = XtraMessageBox.Show("是否添加另一条Action", "消息", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                    if (result == DialogResult.Yes)
                    {
                        //Next step
                        txtRootCause.Text = "";
                        txtTodo.Text = "";
                        dtpDueon.DateTime = DateTime.Now.Date;
                        cbResDep.SelectedIndex = -1;

                    }
                    else
                    {
                        DevMainForm.instance.LoadDeviation(DevMainForm.instance.timeCondition);
                        this.Close();
                    }
                }

            }
            else
            {
                //resDepID = (int)cbResDep.Tag;
                //resPersonID = (int)cbResPerson.Tag;
                //载入当前信息
                DataTable dtOld = SQL.ReturnDataTable3(SystemInfo.SQL, "Todo", $"ID = {TodoID}");
                //是更改项目
                string RootCause = "RootCause='" + txtRootCause.Text + "'";
                string TodoINFO = "TodoINFO='" + txtTodo.Text + "'";
                string RespDepartmentID = "RespDepartmentID=" + resDepID;
                string RespUserID = "RespUserID=" + resPersonID;
                string DueDate = "DueDate='" + dtpDueon.DateTime + "'";
                string Values = $"{RootCause},{TodoINFO},{RespDepartmentID},{RespUserID},{DueDate}";
                if (SQL.Update(SystemInfo.SQL, "Todo", Values, "ID=" + TodoID) == true)
                {

                    //写入历史
                    string Items2 = "Type,TopicID,RootCause,TodoINFO,RespDepartmentID,RespUserID,DueDate,Status,isConfirmation,Modify_userID,Modify_time,Todo_ID,Del_tag";
                    string Values2 = $"'{"修改"}',{TopicID},'{txtRootCause.Text}','{txtTodo.Text}',{resDepID},{resPersonID},'{dtpDueon.DateTime}',{Status},'{isConfirmation}','{SystemInfo.userID}','{DateTime.Now}',{TodoID},{0}";
                    SQL.Insert(SystemInfo.SQL, "Todo_history", Items2, Values2);
                    TodoID = 0;
                    XtraMessageBox.Show("成功修改数据！", "Infomation", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    DevMainForm.instance.LoadDeviation(DevMainForm.instance.timeCondition);
                    this.Close();
                }

            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            foreach (Control control in panelControl1.Controls)
            {
                if (control is MemoEdit Edit)
                {
                    Edit.Text = "";
                }
                if (control is ComboBoxEdit cb)
                {
                    cb.SelectedIndex = -1;
                }

            }
            foreach (Control control in panelControl3.Controls)
            {
                if (control is MemoEdit Edit)
                {
                    Edit.Text = "";
                }
                if (control is ComboBoxEdit cb)
                {
                    cb.SelectedIndex = -1;
                }
            }
            DevMainForm.instance.LoadDeviation(DevMainForm.instance.timeCondition);
            isNewAction = false;
            isNewTopic = false;
            this.Close();
        }

        private void btnClose2_Click(object sender, EventArgs e)
        {
            foreach (Control control in panelControl1.Controls)
            {
                if (control is MemoEdit Edit)
                {
                    Edit.Text = "";
                }

            }
            foreach (Control control in panelControl3.Controls)
            {
                if (control is MemoEdit Edit)
                {
                    Edit.Text = "";
                }
            }
            DevMainForm.instance.LoadDeviation(DevMainForm.instance.timeCondition);
            this.Close();
        }

        private void btnSaveTopic_Click(object sender, EventArgs e)
        {
            if (isNewTopic)
            {

                string[] columnNames = { "DateTime", "TopicINFO", "DepartmentID", "Create_userID", "Create_time", "isEscalation", "Curr_level", "Curr_top", "isCIP", "isComplete", "isClose", "Del_tag", "isUpdate" };
                object[] columnValues = { dtpDateTopic.DateTime, txtTopic.Text, DepTopicID, SystemInfo.userID, DateTime.Now, chkEscalation.Checked, SystemInfo.readLevel, 0, chkCIP.Checked, 0, 0, 0, 0 };
                int res = SQL.InsertDataAndGetId(SystemInfo.SQL, "Topic", columnNames, columnValues);
                if (res > 0)
                {
                    //在历史中写入
                    string Items2 = "Type,DateTime,TopicINFO,DepartmentID,Create_userID,Create_time,isEscalation,Curr_level,Curr_top,isCIP,isComplete,isClose,Del_tag,isUpdate,Topic_ID";
                    string Values2 = $"'{"新增"}','{dtpDateTopic.DateTime}','{txtTopic.Text}',{DepTopicID},{SystemInfo.userID},'{DateTime.Now}',{chkEscalation.Checked},{SystemInfo.readLevel},{0},{chkCIP.Checked},{0},{0},{0},{0},{res}";
                    SQL.Insert(SystemInfo.SQL, "Topic_history", Items2, Values2);
                    MessageBox.Show("成功录入数据！", "Infomation", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    //让用户增加一条Action
                    isNewAction = true;
                    TopicID = res;
                    navigationFrame1.SelectedPageIndex = 0;
                }
                else
                {
                    MessageBox.Show("未能更新数据库", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

            }
            else
            {
                //载入当前信息
                string DT = "DateTime = '" + dtpDateTopic.DateTime + "'";
                string TopicINFO = "TopicINFO = '" + txtTopic.Text + "'";
                string DepartmentID = "DepartmentID = " + cbDepTopic.Tag;
                string isEscalation = "isEscalation = " + Convert.ToInt32(chkEscalation.Checked);
                string Curr_level = "Curr_level = " + SystemInfo.readLevel;
                string isCIP = "isCIP = " + Convert.ToInt32(chkCIP.Checked);
                string Values = $"{DT},{TopicINFO},{DepartmentID},{isEscalation},{Curr_level},{isCIP}";
                if (SQL.Update(SystemInfo.SQL, "Topic", Values, "ID=" + TopicID) == true)
                {
                    //在历史中写入
                    string Items2 = "Type,DateTime,TopicINFO,DepartmentID,isEscalation,Curr_level,Curr_top,isCIP,isComplete,isClose,Del_tag,isUpdate,Modify_userID,Modify_time,Topic_ID";
                    string Values2 = $"'{"修改"}','{dtpDateTopic.DateTime}','{txtTopic.Text}',{cbDepTopic.Tag},{chkEscalation.Checked},{SystemInfo.readLevel},{0},{chkCIP.Checked},{0},{0},{0},{0},{SystemInfo.userID},'{DateTime.Now}',{TopicID}";
                    SQL.Insert(SystemInfo.SQL, "Topic_history", Items2, Values2);
                    TopicID = 0;
                    MessageBox.Show("成功修改数据！", "Infomation", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }

        private int DepTopicID;
        private void cbDepTopic_SelectedValueChanged(object sender, EventArgs e)
        {
            var selectedItem = cbDepTopic.SelectedItem as publicFunc.ComboBoxItem;
            if (selectedItem != null)
            {
                var tag = selectedItem.Tag; // 这里可以使用tag
                DepTopicID = Convert.ToInt32(tag);
            }
        }

        private void navigationFrame1_SelectedPageChanged(object sender, DevExpress.XtraBars.Navigation.SelectedPageChangedEventArgs e)
        {
            if (isNewAction)
            {
                btnSave.Text = "Save new";
                dtpDueon.DateTime = DateTime.Now.Date;
                //查询部门，需要是当前阅读部门下的所有部门
                string depList = SystemInfo.readparentDep.ToString();
                DataTable dt = SQL.ReturnDataTable3(SystemInfo.SQL, "Departments", $"ID = {SystemInfo.readparentDep} or ParentDepartmentID = {SystemInfo.readparentDep}");

            }
        }

        #region 未完成Action显示及编辑
        public int topicID;
        private void LoadAction(int topic)
        {
            DataTable dtSource = new DataTable();
            dtSource.Columns.Add("ID", typeof(int));
            dtSource.Columns.Add("DateTime", typeof(DateTime));
            dtSource.Columns.Add("Assign", typeof(int));
            dtSource.Columns.Add("Topic", typeof(string));
            dtSource.Columns.Add("Rootcause", typeof(string));
            dtSource.Columns.Add("To do/Action", typeof(string));
            dtSource.Columns.Add("Res. department", typeof(string));
            dtSource.Columns.Add("Res. person", typeof(string));
            dtSource.Columns.Add("Due date", typeof(string));

            gcIncomplete.DataSource = dtSource;

            DataTable dtAction = SQL.ReturnDataTable3(SystemInfo.SQL, "View_Todo", $"TopicID = {topic} and isConfirmation = 0");
            if (dtAction.Rows.Count > 0)
            {

            }
        }
        #endregion

        private void btnScore_Click(object sender, EventArgs e)
        {
            if (txtTodo.Text == "")
            {
                XtraMessageBox.Show(LookAndFeel,"未输入Todo信息添加");
                return;
            }
            if (txtRootCause.Text == "")
            {
                DialogResult res = MessageBox.Show("未输入Root cause，是否继续？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (res == DialogResult.No)
                {
                    return;
                }
                if(res == DialogResult.Yes)
                {
                    //打分
                }
            }
        }

    }
}